<template>
  <div>
    <div>
      <el-tree
        ref="tree"
        :data="treeData"
        :props="{ label: 'name' }"
        node-key="id"
        default-expand-all
        show-checkbox
        check-strictly
      />
    </div>

    <el-row class="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" @click="cancelButton">取 消</el-button>
        <el-button
          size="small"
          type="primary"
          @click="setRolesBtn"
        >确 定</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getPermissionList } from '@/api/permission'
import { transTree } from '@/utils/index' // 引入转换为树形结构的方法
import { getRoleId, assignPerm } from '@/api/setting'// 数据回填的接口

export default {
  name: 'AssignPermission',
  props: {
    roleId: {
      type: [Number, String],
      required: true
    }
  },
  data() {
    return {
      treeData: [] // 权限列表树状结构

    }
  },
  created() {
    // console.log(this.roleId)
    this.getPermissionList()// 组件打开获取权限列表
    this.getRoleId()
  },
  methods: {
    // 获取权限列表
    async getPermissionList() {
      const res = await getPermissionList()
      this.treeData = transTree(res.data) // 把树形结构赋值给权限列表
    },

    // 获取某一个角色列表,数据回显
    async  getRoleId() {
      const res = await getRoleId(this.roleId)
      console.log(res)
      this.$refs.tree.setCheckedKeys(res.data.permIds)
    },
    // 取消按钮
    cancelButton() {
      this.$emit('close')
    },

    // 设置权限按钮确认
    async setRolesBtn() {
      // 获取选中项的 ID
      const permIds = this.$refs.tree.getCheckedKeys()
      console.log(permIds)
      // 调用给角色分配权限的接口
      const res = await assignPerm({
        id: this.roleId,
        permIds
      })
      this.$message.success(res.message)
      // 关闭弹框
      this.$emit('close')
    }
  }
}
</script>

<style lang="scss" scoped>
.footer {
  margin-top: 30px;
}
</style>
